/**
* Class Name: ifulfillNewIRQuery 
* Author: Accenture
* Date: 20-Dec-2011
* Requirement/Project Name: iFulfill
* Requirement/Project Description: Contoller for ifulfillOORCreateQuery page
**/


public class ifulfillNewIRQuery 
{
    public fullfilment_item__c fItem{get;set;}
    public Query_Request__C queryReq{get;set;}
    private id recordType = null;
    public List<QueryReasonsCodeWrapper> qrCodeWrapperList {get;set;}
    private Queries__c query = null;
    private final ApexPages.StandardController contrl = null;    
    
    /*
     *  QueryReasonsCode Wrapper Class 
     *
     **/
    
    public class QueryReasonsCodeWrapper
    {
        public Boolean rowSelection {get;set;}
        public Query_Reason_Code__c queryReasonCode {get;set;}
                
        public QueryReasonsCodeWrapper(Boolean sel , Query_Reason_Code__c queryResCode )
        {
                rowSelection =sel;
                queryReasonCode = queryResCode; 
        }
    }
    
    /*
     * Constructor
     *
     **/
    public ifulfillNewIRQuery(ApexPages.StandardController controller) 
    {
         contrl  =  controller;
         qrCodeWrapperList  = new List<QueryReasonsCodeWrapper> ();
         String recID = null;
         query= (Queries__c)controller.getRecord();
         ListViewIds__c listViewIDObj = ListViewIds__c.getInstance(userinfo.getProfileId());         
         recordType =  ApexPages.currentPage().getParameters().get('RecordType');
         string reqId = ApexPages.currentPage().getParameters().get('CF'+listViewIDObj.Query_Request_Field_ID__c+'_lkid');
         recID =ApexPages.currentPage().getParameters().get('id');
         
         if(reqId != null)
             query.query_request_id__c = ApexPages.currentPage().getParameters().get('CF'+listViewIDObj.Query_Request_Field_ID__c+'_lkid');
         
         // Check if record type is fetch from the URL    
         if(recordType !=null)
         {
            query.RecordTypeId = recordType;
         }
            
         List<Query_Request__C> req = [select id,Query_Type__c,Request_Reason__c,Request_Status__c,Request_Comments__c,ownerid,Requestor__c,Requested_Date__c,Request_Aging__c,fulfillment_item__c from query_request__c where id = :query.query_request_id__c ];

         // Check if query has return any value
         if(req.size() > 0)
         {
             queryReq = req[0];
             if(((string)req[0].ownerid).substring(0,3) == '005'){
             query.Query_Request_Owner__c = req[0].ownerid;
             }
             
             List<fullfilment_item__c>  fItemList  = [select Product_Family__c,Sales_Manager1__r.Email,Sales_Manager__c,Sales_Rep_Email__c,Sales_Rep__c,name ,id,status__c,Feature_Code__c,Aging__c,UDAC_Description__c,Function_Sequence__c, UDAC__c, Current_Function_Name__c,Current_Task_Name__c,Item_Id__c, Account__r.Name,Item_Version__c, Region__c,Feature__c, Contract__c,Contract_Version__c,Product_Issue__c,Customer_ID__c, Product_Code__c from fullfilment_item__c where id = : req[0].Fulfillment_Item__c];

             //Check if query has return any value
             if(fItemList.size() > 0 ){
                 fItem = fItemList.get(0);
                    System.debug('fItem --->'+fItem);                
                 // Check if user is editing the existing record or creating new query
                 
                 if(recID == null || recID ==''){
                    listQueryReasonCode();
                 }
                 else{
                     initlizeQueryReasonCode();
                 }      
             }
         } 
    }
    
    /*
     *  Gets the query reason code  to display in the query page based on the product family
     *
     **/
    public void listQueryReasonCode()
    {
        qrCodeWrapperList = new List<QueryReasonsCodeWrapper>();
        List<Query_Reason_Code__c>   queryReasonCodeList  = [Select Reason_Code__c from Query_Reason_Code__c where Product_Family__c = :fItem.Product_Family__c];
        
        for(Query_Reason_Code__c qrcObj: queryReasonCodeList  )
        { 
            qrCodeWrapperList.add(new QueryReasonsCodeWrapper(false,qrcObj));
        }          
    }  
    
    /*
     *  Check if user has selected any query reason code for the query and generate the string
     *
     **/
    public void addQueryReasons()
    {
         String temp = '';
         for (QueryReasonsCodeWrapper wrapObj : qrCodeWrapperList )
         {
             if(wrapObj.rowSelection)
             {
                   temp =   wrapObj.queryReasonCode.Reason_Code__c + ';' + temp;
             }
         } 

        query.Reason_Code_Txt__c = temp.length() > 0 ? temp.subString(0,temp.length() -1 ) : ''; 
     }

    /*
     *     
     *
     **/
    
    public pagereference assignSalesInformation()
    {
          
          ID salesRepID=query.Sales_Rep_Name1__c; 
          ID managerID;
          
          // Clear all the email field content for IR region.
          
          if(fItem.Region__c == IfullfillTextConstant.FI_WORKFLOW_OOR_REG)
          {
              query.Sales_Mgr_Email1__c ='';
              query.Sales_Rep_Email__c='';
          }
          
          if(salesRepID!=null && query.Override_Sales_Rep__c){
              list<User>salesRegInfo=[Select email,Managerid,ID,SFA_Office__c ,SFA_Office_Name__c from User where id= :salesRepID and isActive = true];
              if(salesRegInfo.size()>0){
                   managerID=salesRegInfo.get(0).Managerid;
                   query.Sales_Mgr_Name1__c=managerID;
                   query.Sales_Rep_Email__c=salesRegInfo.get(0).Email;
                   query.Office__c = salesRegInfo.get(0).SFA_Office_Name__c;
                   query.Office_Code__c = salesRegInfo.get(0).SFA_Office__c;               
              }
              list<User>  managerEmail=[Select email from User where id =:managerID];
              if(managerEmail.size() > 0)
              {
                   query.Sales_Mgr_Email1__c=managerEmail.get(0).email;
                   System.debug('salesRepID---'+salesRepID+'managerID '+query.Sales_Mgr_Name1__c+'salesRepEmail'+query.Sales_Rep_Email__c+'managerEmail'+managerEmail[0].email);
         
              }              
          }
          else if(fItem != null && fItem.Sales_Rep__c !=null){
              system.debug('In else loop'+query.Sales_Rep_ID__c );
                  list<User>salesRegInfo=[Select email,Managerid,ID,SFA_Office__c ,SFA_Office_Name__c from User where id= :fItem.Sales_Rep__c and isActive = true];
                  system.debug('In else loop111'+salesRegInfo);
                  if(salesRegInfo.size()>0){
                       query.Office__c = salesRegInfo.get(0).SFA_Office_Name__c;
                       query.Office_Code__c = salesRegInfo.get(0).SFA_Office__c;               
                  }
          }
          
                   
               return null;
    }
    
    /*
     *  override the standard save function
     *
     **/
    
    public PageReference save()
    {
        assignSalesInformation();
        addQueryReasons();
        return contrl.save();
    }

    /* 
     *   Fetch the query reason from  query ReasonsCode object
     *
     **/          
    public void initlizeQueryReasonCode()
    {
        qrCodeWrapperList = new List<QueryReasonsCodeWrapper>();
        List<Query_Reason_Code__c>   queryReasonCodeList  = [Select Reason_Code__c from Query_Reason_Code__c where Product_Family__c = :query.Product_Family__c];
        List<String> queryReasonCode  =  null;                
        Set <String> qrcSet = new Set<String>(); 
        
        if(query.Reason_Code_Txt__c !=null)
        {
           queryReasonCode  =  query.Reason_Code_Txt__c.split(';');
        }
        
        if(queryReasonCode != null)
        {
            for (String obj : queryReasonCode  )
            {
                 qrcSet.add(obj);
            }
        }
        for(Query_Reason_Code__c qrcObj: queryReasonCodeList  )
        { 
            qrCodeWrapperList.add(new QueryReasonsCodeWrapper(qrcSet.contains(qrcObj.Reason_Code__c),qrcObj));
        }          
    }  

}